<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Goods;
use App\Models\GoodsCategory;
use Illuminate\Http\Request;

class GoodsCategoryController extends Controller
{
    // 列表
    public function index(Request $request)
    {
        $searchData = $request->post();

        $model = GoodsCategory::orderBy('id', 'DESC');

        if ($name = $searchData['name'] ?? '') {
            $model->where('name', 'like', "%{$name}%");
        }

        $result = $model->paginate(config('app.limit'));

        return $this->writeJson(0, [
            'data' => $result->items(),
            'count' => $result->total()
        ]);
    }

    // 新增/编辑
    public function add(Request $request)
    {
        $data = $request->post();
        if ($data['id']) {
            $model = GoodsCategory::find($data['id']);
            $model->setRawAttributes($data);
            $model->save($data);
            return $this->writeJson(0, null, '编辑成功');
        } else {
            // 新增
            unset($data['id']);
            $model = new GoodsCategory();
            $model->setRawAttributes($data);
            $model->save();
            return $this->writeJson(0, null, '新增成功');
        }
    }

    // 删除
    public function del(Request $request)
    {
        $id = $request->post('id');
        if (empty($id)) {
            return $this->writeJson(500, null, '参数错误');
        }
        if (Goods::whereCategoryId($id)->count() > 0) {
            return $this->writeJson(500, null, '分类下面已有商品，暂时无法删除');
        }

        GoodsCategory::destroy($id);
        return $this->writeJson(0, null, '删除成功');
    }
}
